package com.hxm.touchdelegate;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.TouchDelegate;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Extend a Child view's Touchable Area.
 * Created by hxm on 2016/9/8
 * <p/>
 * The snippet below does the following:
 * 1.Get the parent view and posts a Runnable on the UI thread.This ensures that the parent lays out its children
 * before calling the getHitRect() method.The getHitRect() method gets the hit rectangle(touchable area) in the
 * parent's coordinates.
 * 2.Finds the TextView child view and calls getHitRect() to get the bounds of the child's touchable area.
 * 3.Extend the bounds of the TextView's hit rectangle.
 * 4.Instantiates a TouchDelegate,passing in the expanded hit rectangle and the TextView child view as parameters.
 * 5.Sets the TouchDelegate on the parent view,such that touches within the touch delegate bounds are routed to the
 * child.
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Get the parent view
        View rootView = findViewById(R.id.root_view);
        rootView.post(new Runnable() {
            //Post in the parent's message queue to make sure the parent lays out
            //its children before you call getHitRect()
            @Override
            public void run() {
                //The bounds for the delegate view(An TextView in this example)
                Rect delegateArea = new Rect();
                TextView textView = (TextView) findViewById(R.id.text_view);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, "onclick", Toast.LENGTH_SHORT).show();
                    }
                });
                //The hit rectangle for the TextView
                textView.getHitRect(delegateArea);
                //Extend the touch area of the TextView beyond its bounds
                //on the right and bottom
                delegateArea.right += 100;
                delegateArea.bottom += 100;
                //Instantiate a TouchDelegate.
                TouchDelegate touchDelegate = new TouchDelegate(delegateArea, textView);
                //Sets the TouchDelegate on the parent view,such that touches
                //within the touch delegate bounds are routed to the child.
                if (View.class.isInstance(textView.getParent())) {
                    ((View) textView.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }
}
